import { ExportOutlined, GlobalOutlined, LinkOutlined } from '@ant-design/icons';
import {
  ActionType,
  PageContainer,
  ProForm,
  ProFormCascader,
  ProFormDateRangePicker,
  ProFormRadio,
  ProFormSelect,
  QueryFilter,
} from '@ant-design/pro-components';
import { Button, Cascader, Form, FormInstance, Image, Input, Space, Tag, Typography } from 'antd';
import RcResizeObserver from 'rc-resize-observer';
import React, { useEffect, useRef, useState } from 'react';

import { getApi } from '@/requestConfig';
import {
  getPretreatmentRecordAreaCascaders,
  getPretreatmentRecordChannelList,
  getPretreatmentRecordSourceList,
  pagePretreatmentRecord,
} from '@/services/api/api-datahub-record';
import { useAccess } from 'umi';
import moment from 'moment';
import CheckboxRadio from './ChannelCheckboxRadio';
import DetialRecord from './DetailRecord';
import ProList from '@ant-design/pro-list';
const { Paragraph, Text } = Typography;

interface PageContainerDatahubRecordProps { }

const PageContainerDatahubRecord: React.FC<PageContainerDatahubRecordProps> = (props) => {
  const access = useAccess();
  const [responsive, setResponsive] = useState(false);
  const [width, setWidth] = useState(500);
  const formRef = useRef<FormInstance>();
  const userRef = useRef<ActionType>();
  const [channelList, setChannelList] = useState<CuesTopicData.ChannelList[]>([]);
  const [sources, setSourceState] = useState<DatahubRecordData.SourceList[]>([]);
  const [sourceSelectChannelIds, setSourceSelectChannelIdsState] = useState<string[]>([]);
  const [sourceOptions, setSourceOptions] = useState<DatahubRecordData.SourceList[]>([]);
  const [areaList, setAreaList] = useState([]);
  const [total, setTotal] = useState(0);
  /**
   * 搜索参数
   */
  const [queryParam, setQueryParamState] = useState({
    dataReleaseTimes: [moment().subtract(89, 'days'), moment()],
  });

  const getChannelList = async () => {
    const res = await getPretreatmentRecordChannelList();
    if (res.code === 0) {
      if (Array.isArray(res.data) && res.data.length > 0) {
        const list = res.data.map((item) => {
          return {
            label: item.name,
            value: item.id
          }
        })
        setChannelList(list);
      }
    }

  };

  /**
   * 请求网络
   * @param value
   */
  const request = async (params = {}) => {
    const response = await pagePretreatmentRecord({ ...params, ...queryParam });
    setTotal(response.data.total);
    return Promise.resolve({
      data: response.data.data,
      total: response.data.total,
      success: response.code === 0,
    });
  };

  const getShowSourceList = (list: DatahubRecordData.SourceList[]) => {
    //级联数据
    let cascaderSourcesData = new Array();
    //分组处理
    const sourcesGroupByData = list.reduce((acc, item) => {
      const key = item.levelName;
      if (!acc[key]) {
        acc[key] = [];
      }
      acc[key].push(item);
      return acc;
    }, {});

    if (sourcesGroupByData.中央媒体 !== undefined) {
      cascaderSourcesData.push({
        value: 1000,
        label: '中央媒体',
        children: sourcesGroupByData.中央媒体
          .sort((n1: { seq: number }, n2: { seq: number }) => {
            return n1.seq - n2.seq;
          })
          .map((item: { id: string; name: string; channelId: string; channelName: string }) => {
            return {
              value: item.id,
              label: `${item.name} - ${item.channelName}`,
              channelId: item.channelId,
            };
          }),
      });
    }

    if (sourcesGroupByData.市属媒体 !== undefined) {
      cascaderSourcesData.push({
        value: 2000,
        label: '市属媒体',
        children: sourcesGroupByData.市属媒体
          .sort((n1: { seq: number }, n2: { seq: number }) => {
            return n1.seq - n2.seq;
          })
          .map((item: { id: string; name: string; channelId: string; channelName: string }) => {
            return {
              value: item.id,
              label: `${item.name} - ${item.channelName}`,
              channelId: item.channelId,
            };
          }),
      });
    }

    if (sourcesGroupByData.区县媒体 !== undefined) {
      cascaderSourcesData.push({
        value: 3000,
        label: '区县媒体',
        children: sourcesGroupByData.区县媒体
          .sort((n1: { seq: number }, n2: { seq: number }) => {
            return n1.seq - n2.seq;
          })
          .map((item: { id: string; name: string; channelId: string; channelName: string }) => {
            return {
              value: item.id,
              label: `${item.name} - ${item.channelName}`,
              channelId: item.channelId,
            };
          }),
      });
    }

    return cascaderSourcesData;
  };

  /**
   * 获取来源列表
   * @param value
   */
  const getSourceList = async (media: string) => {
    const response = await getPretreatmentRecordSourceList();

    if (response.code === 0) {
      setSourceOptions(getShowSourceList(response.data));
      setSourceState(response.data);
    }
  };

  const getAreaList = async () => {
    const res = await getPretreatmentRecordAreaCascaders();
    setAreaList(res.data);
  };

  useEffect(() => {
    getSourceList(' ');
    getAreaList();
    getChannelList();
  }, []);

  return (
    <>
      <QueryFilter
        submitter={false}
        span={24}
        labelWidth="auto"
        formRef={formRef}
        initialValues={{
          channelIds: [], //渠道=全部
          levelId: 'all', //媒体=全部
          sourceIds: [], //媒体选择框=空
          area: '500000000000', //区域=重庆
          areaIds: [], //区域选择框=空
          time: '最近90天',
          dataReleaseTimes: [moment().subtract(89, 'days'), moment()],
        }}
        layout="horizontal"
        onFinish={async (value) => {
          console.log('====1==onFinish====', value);

          if (value.levelId === 'all' || value.levelId === 'clear' || value.levelId === '') {
            value.levelIds = [];
          } else {
            value.levelIds = [value.levelId];
          }

          if (value.sourceIds != undefined && value.sourceIds.length !== 0) {
            let sourceIds = new Array();

            value.sourceIds.forEach((item: any[]) => {
              if (item.length == 1) {
                sourceIds = sourceIds.concat(
                  sources.filter((i) => i.levelId == item[0].toString()).map((i) => i.id),
                );
              } else {
                const option = item[item.length - 1];
                sourceIds.push(option);
              }
            });
            value.sourceIds = sourceIds;
          }

          if (value.areaIds != undefined && value.areaIds.length !== 0) {
            let areaIds = new Array();

            value.areaIds.forEach((item: any[]) => {
              const option = item[item.length - 1];
              areaIds.push(option);
            });

            value.areaIds = areaIds;
          }

          console.log('====2==onFinish====', value);

          setQueryParamState({ ...queryParam, ...value });
          userRef.current?.reloadAndRest();
        }}
      >
        <ProForm.Group >
          <div
            style={{
              display: 'flex',
              width: (width / 3) * 2,
            }}
          >
            <Form.Item name="dataName" style={{ maxWidth: (width / 3) * 2, width: '100%' }}>
              <Input.Search
                placeholder="搜索"
                enterButton="搜索"
                allowClear
                onSearch={(value) => {
                  formRef.current?.setFieldValue('dataName', value);
                  formRef.current?.submit();
                }}
              />
            </Form.Item>
          </div>
        </ProForm.Group>
        <ProForm.Group title="渠道">
          <ProFormSelect
            name="channelIds"
            options={[
              {
                label: '全部',
                value: 0
              }, ...channelList
            ]}
            fieldProps={{
              style: {
                width: (width / 3) * 1.5,
              },
              mode: 'multiple',
              allowClear: true,
              onChange(value, option) {
                formRef.current?.setFieldValue('channelIds', value);
                formRef.current?.setFieldValue('sourceIds', []);
                formRef.current?.submit();
              },
            }}
          />
        </ProForm.Group>

        <ProForm.Group title="媒体">
          <ProFormCascader
            name="sourceIds"
            placeholder="选择媒体"
            allowClear
            fieldProps={{
              options: sourceOptions,
              style: {
                width: (width / 3) * 1.5,
              },
              multiple: true,
              allowClear: true,
              showSearch: true,
              maxTagCount: 'responsive',
              showCheckedStrategy: Cascader.SHOW_PARENT,
              displayRender: (labels: string[], selectedOptions?: any[]) => {
                return labels.map((label, i) => {
                  const option = selectedOptions[i];
                  if (i === labels.length - 1) {
                    return <span key={option.value}>{label}</span>;
                  }
                  return <span key={option.value}>{label} / </span>;
                });
              },
              onClear() {
                formRef.current?.setFieldValue('levelId', 'clear');
                formRef.current?.submit();
              },
              onChange(value, selectOptions) {
                const levelId = formRef.current?.getFieldValue('levelId');

                if (levelId === 'clear') {
                  setSourceOptions(getShowSourceList(sources));
                  formRef.current?.setFieldValue('levelId', 'all');
                  setSourceSelectChannelIdsState([]);
                  formRef.current?.setFieldValue('channelIds', []);
                } else {
                  if (selectOptions.length === 0) {
                    formRef.current?.setFieldValue('levelId', 'all');
                  } else {
                    //清除 媒体 button 选中
                    formRef.current?.setFieldValue('levelId', '');

                    let setChannelIds = new Set<string>();

                    console.log('======selectOptions======', selectOptions);

                    selectOptions.forEach((item) => {
                      if (item.length == 1) {
                        item[0].children.forEach((i: { channelId: string; }) => {
                          setChannelIds.add(i.channelId);
                        });
                      } else {
                        const option = item[item.length - 1];
                        setChannelIds.add(option.channelId);
                      }
                    });

                    console.log('=================', [...setChannelIds]);

                    setSourceSelectChannelIdsState([...setChannelIds]);
                    formRef.current?.setFieldValue('channelIds', [...setChannelIds]);
                  }
                }
                formRef.current?.submit();
              },
            }}
          />
        </ProForm.Group>

        <ProForm.Group title="区域">
          <ProFormCascader
            name="areaIds"
            placeholder="选择区域"
            // initialValue={['1']}
            fieldProps={{
              options: areaList,
              style: {
                width: (width / 4) * 2,
              },
              multiple: true,
              allowClear: true,
              showSearch: true,
              maxTagCount: 'responsive',
              showCheckedStrategy: Cascader.SHOW_PARENT,
              onClear() {
                formRef.current?.setFieldValue('area', 'clear');
                formRef.current?.submit();
              },
              onChange: (e) => {
                const area = formRef.current?.getFieldValue('area');

                console.log('=========', area);

                if (area === 'clear' || area === '') {
                  formRef.current?.setFieldValue('area', '500000000000');
                } else {
                  formRef.current?.setFieldValue('area', '');
                }
                formRef.current?.submit();
              },
            }}
          />
        </ProForm.Group>

        <ProForm.Group title="发布时间">
          <ProFormDateRangePicker
            name="dataReleaseTimes"
            fieldProps={{
              style: {
                width: (width / 4.5) * 2,
              },
              onChange(dates, dateStrings) {
                formRef.current?.setFieldValue('time', ' ');
                formRef.current?.submit();
              },
            }}
          />
        </ProForm.Group>
      </QueryFilter>
      <ProList<DatahubRecordData.PretreatmentRecordPage>
        ghost
        actionRef={userRef}
        headerTitle={
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <span>
              搜索得到：<span style={{ color: 'red', alignItems: 'center' }}>{total}</span>条
            </span>
            <div>
              <Button
                type="primary"
                size='small'
                style={{ marginLeft: 10 }}
                icon={<ExportOutlined />}
                onClick={() => {
                  console.log(formRef.current?.getFieldsValue());
                  const time = formRef.current?.getFieldValue('dataReleaseTimes');
                  const param = 'startTime=' + time[0] + '&' + 'endTime=' + time[1];
                  const exportExcelUrl = getApi() + '/datahub/pretreatment/record/export?' + param;
                  window.open(exportExcelUrl);
                }}
              >
                数据导出
              </Button>
              <Button type="primary" onClick={() => userRef.current?.reload()} size='small' style={{ marginLeft: 10 }}>
                刷新
              </Button>
            </div>
          </div>
        }
        pagination={{
          defaultPageSize: 20,
          showSizeChanger: true,
        }}
        // toolBarRender={() => [
        //   <span>
        //     搜索得到：<span style={{ color: 'red' }}>{total}</span>条
        //   </span>,
        //   <Button
        //     type="primary"
        //     size='small'
        //     icon={<ExportOutlined />}
        //     onClick={() => {
        //       console.log(formRef.current?.getFieldsValue());
        //       const time = formRef.current?.getFieldValue('dataReleaseTimes');
        //       const param = 'startTime=' + time[0] + '&' + 'endTime=' + time[1];
        //       const exportExcelUrl = getApi() + '/datahub/pretreatment/record/export?' + param;
        //       window.open(exportExcelUrl);
        //     }}
        //   >
        //     数据导出
        //   </Button>,
        //   <Button type="primary" onClick={() => userRef.current?.reload()} size='small'>
        //     刷新
        //   </Button>,
        // ]}
        // toolbar={{

        // }}
        request={request}
        itemLayout="vertical"
        rowKey="id"
        grid={{ gutter: 18, column: 1 }}
        metas={{
          title: {
            render: (dom, entity) => (
              <div style={{ display: 'flex', justifyContent: 'space-between', flexDirection: 'column' }}>
                <div style={{ display: 'inline-block' }}>
                  {access.数据仓x配置x运营员 && (
                    <Tag color={entity.isExamine == 0 ? 'red' : 'green'}>
                      {entity.isExamine == 0 ? '未审核' : '已审核'}
                    </Tag>
                  )}
                  <Tag icon={<GlobalOutlined />} color="#55acee" style={{ display: 'inline-block' }}>
                    {entity.sourceName}
                  </Tag>
                  {/* <EditData
                    onRefurbish={userRef.current?.reload}
                    detailData={entity}
                    name={entity.dataName}
                  /> */}
                  <DetialRecord
                    dataId={entity.id}
                    dataName={entity.dataName}
                    onRefurbish={userRef.current?.reload}
                  />
                </div>
                <div>
                  <div style={{ textAlign: 'left' }}>
                    <a href={entity.dataSourceUrl} target="_blank" rel="noopener noreferrer">
                      <LinkOutlined />
                      查看原文
                    </a>
                    <span> 发布时间：{entity.dataReleaseTime}</span>
                  </div>
                  <div style={{ textAlign: 'left', marginTop: 5 }}>
                    标签：
                    {entity?.labels.slice(0, 10).map((item) => (
                      <Tag>{item?.name}</Tag>
                    ))}
                    {entity?.labels.length > 3 ? <Tag>...</Tag> : ''}
                  </div>
                  {('微信' == entity.channelName ||
                    '抖音' == entity.channelName ||
                    '今日头条' == entity.channelName ||
                    '微博' == entity.channelName) && (
                      <div style={{ textAlign: 'left', marginTop: 5 }}>
                        <Space size="large">
                          <span>点赞量：{entity.dataLikeCount}</span>
                          <span>评论量：{entity.dataCommentCount}</span>
                          <span>阅读量：{entity.dataReadCount}</span>
                          <span>转发量：{entity.dataForwardingCount}</span>
                          {'微信' == entity.channelName && <span>在看量：{entity.dataWatchCount}</span>}
                          {'抖音' == entity.channelName && <span>播放量：{entity.dataPlayCount}</span>}
                        </Space>
                      </div>
                    )}
                </div>
              </div>
            ),
          },
          description: {
            render: (dom, entity) => (
              <>
                {entity.levelName && (
                  <Tag
                    color={
                      entity.levelId === '1000'
                        ? 'error'
                        : entity.levelId === '2000'
                          ? 'warning'
                          : 'success'
                    }
                  >
                    {entity.levelName}
                  </Tag>
                )}
                {entity.channelName && <Tag color="success">{entity.channelName}</Tag>}
                {entity.focusName && <Tag color="processing">{entity.focusName}</Tag>}
                {entity?.areas?.map((item) => (
                  <Tag>{item?.name}</Tag>
                ))}
              </>
            ),
          },
          content: {
            render: (dom, entity) => {
              if ('广大' == entity.factoryName) {
                if ('电视视频' == entity.channelName) {
                  return (
                    <div>
                      <Paragraph ellipsis={{ rows: 4, expandable: true, symbol: '查看更多' }}>
                        {entity.dataAbstracts}
                      </Paragraph>
                    </div>
                  );
                }
              } else {
                if ('电视视频' == entity.channelName) {
                  return (
                    <div>
                      <Paragraph ellipsis={{ rows: 4, expandable: true, symbol: '查看更多' }}>
                        {entity.dataAbstracts}
                      </Paragraph>
                    </div>
                  );
                } else if ('电子报纸' == entity.channelName) {
                  return (
                    <div>
                      <Paragraph ellipsis={{ rows: 4, expandable: true, symbol: '查看更多' }}>
                        {entity.dataAbstracts}
                      </Paragraph>
                    </div>
                  );
                } else if ('微信' == entity.channelName) {
                  return (
                    <div>
                      <Paragraph ellipsis={{ rows: 4, expandable: true, symbol: '查看更多' }}>
                        {entity.dataAbstracts}
                      </Paragraph>
                    </div>
                  );
                } else if ('微博' == entity.channelName) {
                  return false;
                } else if ('今日头条' == entity.channelName) {
                  return false;
                } else {
                  return false;
                }
              }
            },
          },
        }}
      />
    </>
  );
};

export default PageContainerDatahubRecord;
